package com.youlei.newgraduateproject.controller;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.youlei.newgraduateproject.common.dto.SysMenuDto;
import com.youlei.newgraduateproject.entity.CommonResult;
import com.youlei.newgraduateproject.entity.SysMenu;
import com.youlei.newgraduateproject.entity.SysRoleMenu;
import com.youlei.newgraduateproject.entity.SysUser;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author youlei
 * @since 2021-05-08
 */
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController extends BaseController {

    /**
     * 获取当前用户的菜单导航栏以及权限
     * nav navigation
     */
    @GetMapping("/nav")
    public CommonResult nav(Principal principal) {
        //使用security中的方法获取当前用户的用户名
        String username = principal.getName();
        //根据用户名获取用户信息
        SysUser sysUser = sysUserService.getByUserName(username);
        //通过逗号将权限信息分隔开来装入数组中,如ROLE_Admin,sys:user:save
        String[] authoritys = StringUtils
                .tokenizeToStringArray(sysUserService.getUserAuthorityInfo(sysUser.getId()), ",");

        List<SysMenuDto> navs = sysMenuService.getCurrentUserNav();

        return new CommonResult(200,
                "获取菜单导航栏以及权限信息",
                MapUtil.builder()
                        .put("nav", navs)
                        .put("authoritys", authoritys)
                        .map());
    }


    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public CommonResult info(@PathVariable(name = "id") Long id) {
        return new CommonResult(sysMenuService.getById(id));
    }

    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public CommonResult list() {

        List<SysMenu> menus = sysMenuService.tree();
        return new CommonResult(menus);
    }

    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:menu:save')")
    public CommonResult save(@Validated @RequestBody SysMenu sysMenu) {

        //sysMenu.setCreated(LocalDateTime.now());

        sysMenuService.save(sysMenu);
        return new CommonResult(sysMenu);
    }

    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:menu:update')")
    public CommonResult update(@Validated @RequestBody SysMenu sysMenu) {

        //sysMenu.setUpdated(LocalDateTime.now());

        sysMenuService.updateById(sysMenu);

        // 清除所有与该菜单相关的权限缓存
        sysUserService.clearUserAuthorityInfoByMenuId(sysMenu.getId());
        return new CommonResult(sysMenu);
    }

    @PostMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    public CommonResult delete(@PathVariable("id") Long id) {

        int count = sysMenuService.count(new QueryWrapper<SysMenu>().eq("parent_id", id));
        if (count > 0) {
            return new CommonResult(400,"请先删除子菜单");
        }

        // 清除所有与该菜单相关的权限缓存
        sysUserService.clearUserAuthorityInfoByMenuId(id);

        sysMenuService.removeById(id);

        // 同步删除中间关联表
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("menu_id", id));
        return new CommonResult("");
    }


}
